//
//  GBReportTableView.m
//  警用舆情平台
//
//  Created by 郭斌 on 15/6/20.
//  Copyright (c) 2015年 魏强. All rights reserved.
//

#import "GBReportTableView.h"
#import "GBRequest.h"
#import "MJRefresh.h"
#import "Cell5_3.h"
#import "GBModel.h"
#import "UIImageView+WebCache.h"
#import "GBSingleWebViewController.h"
#import "Reachability.h"

#define baseUrl @"&method=getMobileReportList&token="
#define page @"&p="
#define limit @"&limit=10"
#define countt @"&count="

@interface GBReportTableView () <UITableViewDataSource,UITableViewDelegate,GBRequestDelegate>
{
    //记录每个tableview的当前页
    int _currentPage;
    
    BOOL noDataNew; //判断是否应该刷新
    //4.16改
    NSString *refreshUrl; //下拉加载更多的url
    //MBProgressHUD *_hud;
    int allCount; //所有数据的个数
    int limitCount; //现在数据的条数
    
    //8.11
    NSMutableArray *photoArr; //照片的数组
    
    //8.25
    NSArray *reportArr; //上报类型数组
    NSArray *informationTypeArr; //信息类别数组
    NSArray *geographyArr; //物理地域数组
    NSArray *activityArr; //活动形式数组
    NSArray *informationLevelArr; //信息等级数组
    NSArray *informationRegionArr; //信息归属地数组
    NSArray *mainWordArr; //主关键字数组
    NSArray *secondWordArr; //次关键字数组
}
@end

@implementation GBReportTableView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        //收到删除时候
        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteAction:) name:@"deleShow" object:nil];
        //收到刷新的通知
        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startRequest) name:@"reloadTheCollectview" object:nil];
        reportArr = @[@"本地舆情",@"本省舆情",@"工作报告",@"引导申请",@"落地申请"];
        informationTypeArr = @[@"单条",@"综合",@"约稿",@"工作报告",@"紧急敏感",@"引导申请",@"落地申请"];
        geographyArr = @[@"不详",@"境内",@"境外"];
        activityArr = @[@"网名转载转帖",@"发表公开信/呼吁书",@"发表过激言论",@"网上煽动",@"网上签名",@"网上组织、策划、勾联",@"媒体网站报道",@"涉本市领导人",@"论坛微博"];
        informationLevelArr = @[@"普通",@"急件",@"加急",@"特急",@"特提"];
        informationRegionArr = @[@"非本地",@"本地"];
        mainWordArr = @[@"网上舆论热点",@"涉日",@"维权",@"各类思潮",@"法轮功信息",@"宗教",@"涉警舆论",@"反恐信息",@"网络安全事件",@"涉嫌失泄密",@"工作报告",@"敌对组织活动",@"组党结社",@"周边国家及地区",@"奥运",@"舆情工作",@"其它"];
        secondWordArr = @[@"国家领导人活动",@"重要会议",@"国家重大方针、政策",@"境外重大事件",@"重大司法案件",@"其他"];
        
//        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7 target:self selector:@selector(lateeeee) userInfo:nil repeats:NO];
        //初始化
        _currentPage = 1;
        limitCount = 10;
        allCount = 20;
        self.data = [NSMutableArray array];
        photoArr = [NSMutableArray array];
        //_url = [NSString string];
        self.rowHeight = 90;
        self.tableFooterView = [[UIView alloc] init];
        self.delegate = self;
        self.dataSource = self;
        [self registerClass:[Cell5_3 class] forCellReuseIdentifier:@"Cell5_3"];
        //去掉下划线
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self lateeeee];
    }
    return self;
}

#pragma mark - 接收到删除的点击按钮通知
-(void)deleteAction:(NSNotification *)note
{
    NSDictionary *user = [note userInfo];
    NSString *url = [user objectForKey:@"deletetS"];
    //NSLog(@"%@",url);
    int jji = [url intValue];
    //NSLog(@"%d",jji);
    [self.data removeObjectAtIndex:jji];
    [self reloadData];
}

#pragma mark - 延时
-(void)lateeeee
{
//    __weak typeof(self) weakSelf = self;
    
    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(startRequest)];
    // 马上进入刷新状态
    // 添加传统的上拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    MJRefreshAutoNormalFooter *fooder = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [fooder setTitle:@"" forState:MJRefreshStateIdle];
    self.footer = fooder;
    // 添加传统的上拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    /**
     也可以这样使用
     [self.tableView.header beginRefreshing];
     此时self.tableView.header == self.tableView.legendHeader
     */
}
- (void)setJurl:(NSString *)Jurl{
    _Jurl = Jurl;
    [self.header beginRefreshing];
}
#pragma mark - 上拉加载更多
-(void)loadMoreData
{
    //判断当前是否有新数据
    if(limitCount < allCount)
    {
        limitCount += 10;
        _currentPage++;
        [self startRequest2];
    }
    else
    {
        [self.footer endRefreshing];
    }
}

#pragma mark - 开始请求数据
-(void)startRequest
{
    //重新刷新 重置数据
    limitCount = 10;
    _currentPage = 1;
    //检查当前网络状态
    
    //清空数组
    [self.data removeAllObjects];
    //NSLog(@"基本url:%@",_Jurl);
    GBRequest *request1 = [[GBRequest alloc]initWithUrlStr:_Jurl];
//    NSString* webStringURL = [_Jurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSString *urlStr = [webStringURL stringByReplacingOccurrencesOfString:@"+" withString:@"%2B" options:NSLiteralSearch range:NSMakeRange(0, webStringURL.length)];
//    request1.url = [NSURL URLWithString:_Jurl];
    request1.tag = 1;
    
    request1.delegate = self;
    [request1 startRequestData];
}

#pragma mark - 上拉加载更多数据
-(void)startRequest2
{
    KDAccount *account = [KDAccountTool account];
    refreshUrl = [NSString stringWithFormat:@"%@%@%@%@%d%@&count=%d", ServerActionAddr, baseUrl,account.tokens,page,_currentPage,limit,allCount];
    //NSLog(@"###2 %@",refreshUrl);
    GBRequest *request1 = [[GBRequest alloc]initWithUrlStr:refreshUrl];
    request1.tag = 1;
    request1.delegate = self;
    [request1 startRequestData];
}

#pragma mark - 数据成功请求完毕
- (void)requestDidFinished:(GBRequest *)request
{
    NSString *str = [[NSString alloc] initWithData:request.requestData encoding:NSUTF8StringEncoding];
    //解析
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    id dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *jsonDict = nil;
    if ([dataArray isKindOfClass:[NSDictionary class]])
    {
        jsonDict = dataArray;
        //NSLog(@"%@",jsonDict[@"status"]);
    }
    //NSLog(@"%@",jsonDict[@"info"]);
    //数据总个数
    if([jsonDict[@"count"] isKindOfClass:[NSNumber class]])
    {
        id countAll = jsonDict[@"count"];
        allCount = [countAll intValue];
    }
    
    NSMutableArray *info = jsonDict[@"data"];
    
    // 判断数据是否为空
    if ([info isKindOfClass:[NSNull class]])
    {
        //停止更新数据
        [self.header endRefreshing];
        [self.footer endRefreshing];
        return;
    }
    for(NSDictionary *dic in info)
    {
        GBModel *model = [[GBModel alloc] init];
        model.photoArray = [NSMutableArray array];
        //获取照片
        NSArray *dicc = dic[@"filepath"];
        for(int i = 0; i < dicc.count; i++)
        {
            NSString *photoUrl = [dicc[i] objectForKey:@"filePath"];
            //NSLog(@"photoUrl = %@",photoUrl);
            if(![photoUrl isEqualToString:@""])
            {
                [model.photoArray addObject:photoUrl];
            }
        }
        
        long long time= [dic[@"reportTime"] longLongValue ];
//        NSString *str = [NSString stringWithFormat:@"%@", time];
//        long long times = [str longLongValue];
        NSDate *d = [[NSDate alloc] initWithTimeIntervalSince1970:time/1000.0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *strDate = [dateFormatter stringFromDate:d];
        model.date = [NSString stringWithFormat:@"%@",strDate];
        
        long long time2 = [dic[@"ori_messageTime"] longLongValue];
        NSDate *d2 = [[NSDate alloc] initWithTimeIntervalSince1970:time2/1000.0];
        NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
        [dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *strDate2 = [dateFormatter stringFromDate:d2];
        model.ori_messageTime = [NSString stringWithFormat:@"%@",strDate2];
        
        model.docId = dic[@"docIdStr"];
        model.fav_id = [dic[@"fav_id"] intValue];
        //NSLog(@"%@",dic[@"docId"]);
        model.title = dic[@"reportTitile"];
        id favid = dic[@"fav_id"];
        model.fav_id = [favid intValue];
        id typep = dic[@"clueType_id"];
        model.type = [typep intValue];
        id uid = dic[@"u_id"];
        model.u_id = [uid intValue];
        model.url = dic[@"url"];
        model.ori_title = dic[@"ori_title"];
        id webType = dic[@"ori_websiteType"];
        model.ori_websiteType = [NSString stringWithFormat:@"%d",[webType intValue]];
        
        id reportTy = dic[@"reportType"];
        int reportId = [reportTy intValue];
        model.reportType = [NSString stringWithFormat:@"%@" ,reportArr[reportId]];
        
        id informationTy = dic[@"infoType"];
        int infoId = [informationTy intValue];
        
        if(infoId >= informationTypeArr.count)
        {
            model.infoType = [NSString stringWithFormat:@"%@" ,informationTypeArr[informationTypeArr.count - 1]];
        }
        else
        {
            model.infoType = [NSString stringWithFormat:@"%@" ,informationTypeArr[infoId]];
        }
        
        model.recheckPeople = dic[@"recheckPeople"];
        model.approvePeople = dic[@"approvePeople"];
        
        id geogphrayR = dic[@"physicsRegion"];
        int geog = [geogphrayR intValue];
        model.physicsRegion = [NSString stringWithFormat:@"%@" ,geographyArr[geog]];
        
        id reportStatus1 = dic[@"isSync"];
        int reportStatus2 = [reportStatus1 intValue];
        model.reportStatus = reportStatus2;
        
        id activit = dic[@"activeType"];
        int acti = [activit intValue];
        model.activeType = [NSString stringWithFormat:@"%@" ,activityArr[acti]];
        
        id informationLevel = dic[@"infoLevel"];
        int infoLe = [informationLevel intValue];
        model.infoLevel = [NSString stringWithFormat:@"%@" ,informationLevelArr[infoLe]];
        
        id informationR = dic[@"isLocal"];
        int infoRe = [informationR intValue];
        if(infoRe >= informationRegionArr.count)
        {
            infoRe = (int)informationRegionArr.count - 1;
        }
        model.isLocal = [NSString stringWithFormat:@"%@" ,informationRegionArr[infoRe]];
        
        id mainWo = dic[@"mainKeyWord"];
        int mainW = [mainWo intValue];
        model.mainKeyWord = [NSString stringWithFormat:@"%@" ,mainWordArr[mainW]];
        
        id subKey = dic[@"subKeyWord"];
        int subk = [subKey intValue];
        model.subKeyWord = [NSString stringWithFormat:@"%@" ,secondWordArr[subk]];
        
        id regio = dic[@"region"];
        model.region = [NSString stringWithFormat:@"%d" ,[regio intValue]];
        model.ori_messageContent = dic[@"ori_messageContent"];
        model.ori_websiteName = dic[@"ori_websiteName"];
        model.ori_author = dic[@"ori_author"];
        model.otherDescription = dic[@"otherDescription"];
        model.workRequirement = dic[@"workRequirement"];
        model.content = dic[@"reportContent"];
        model.clueType_id = [dic[@"clue_id"] intValue];
        model.ori_messageURL = dic[@"ori_messageURL"];
        [self.data addObject:model];
        //[self reloadData];
    }
    
    [self reloadData];
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
    //NSLog(@"%@",jsonDict);
}

#pragma mark - 数据请求失败
- (void)requestDidFailedWithError:(NSError *)error
{
    UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [messageView show];
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
}

#pragma mark - tableview返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell5_3";
    Cell5_3 *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if(self.data.count > 0)
    {
        GBModel *model = self.data[indexPath.row];
        cell.titleLabel1.text = model.title;
        //cell.titleLabel1.font = [UIFont systemFontOfSize:19];
        cell.titleLabel1.font = [UIFont boldSystemFontOfSize:17];
        cell.titleLabel1.textColor = [UIColor colorWithRed:(64.0 / 255.0) green:(64.0 / 255.0) blue:(64.0 / 255.0) alpha:1];
        cell.titleLabel1.frame = CGRectMake(10, -8, self.frame.size.width - 20, 60);
        
        cell.timeLabel.text = model.date;
        cell.timeLabel.font = [UIFont systemFontOfSize:12];
        
        if(model.reportStatus == 0)
        {
            cell.reportStatusLabel.text = @"没有";
        }
        else if(model.reportStatus == 1)
        {
            cell.reportStatusLabel.text = @"同步中";
        }
        else
        {
            cell.reportStatusLabel.text = @"已完成";
        }
        
        if(model.type == 0)
        {
            cell.comeFromLabel.text = @"新闻";
        }
        else if(model.type == 1)
        {
            cell.comeFromLabel.text = @"电子报";
        }
        else if(model.type == 2)
        {
            cell.comeFromLabel.text = @"视频";
        }
        else if(model.type == 3)
        {
            cell.comeFromLabel.text = @"短信";
        }
        else if(model.type == 4)
        {
            cell.comeFromLabel.text = @"微信";
        }
        else if(model.type == 5)
        {
            cell.comeFromLabel.text = @"QQ群";
        }
        else if(model.type == 6)
        {
            cell.comeFromLabel.text = @"论坛";
        }
        else if(model.type == 7)
        {
            cell.comeFromLabel.text = @"微博";
        }
        else if(model.type == 8)
        {
            cell.comeFromLabel.text = @"境外媒体";
        }
        cell.neiRong.text = model.content;
        //NSLog(@"arr = %@",model.photoArray);
        //定制cell右按钮
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

//cell选中执行
#pragma mark - 当单元格被选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger count = self.data.count;
    //NSLog(@"$$$");
    if(count != 0)
    {
        GBModel *model = self.data[indexPath.row];
        NSString *clueId = [NSString stringWithFormat:@"%d",model.clueType_id];
        NSString *clueTypeId = [NSString stringWithFormat:@"%d",model.type];
        //NSLog(@"%@",single.whichPage);
        NSDictionary *userInfo11b = [[NSDictionary alloc] initWithObjectsAndKeys:model.title,@"singleTitle",model.date,@"singleDate",clueId,@"singleClueId",model.workRequirement,@"singleWorkAsk",model.content,@"singleNeiRong",model.otherDescription,@"singleDescription",clueTypeId,@"singleClueTypeId",model.ori_messageURL,@"singleWhichType",model.region,@"singleRegion",model.ori_websiteType,@"singleWebsiteType",model.ori_author,@"singleAuthor",model.ori_websiteName,@"singleWebName",model.ori_messageTime,@"singleMessageTime",model.ori_messageContent,@"singleMessageContent",model.photoArray,@"singlePhotoUrlArray",model.reportType,@"reportType",model.infoType,@"infoType",model.recheckPeople,@"recheckPeople",model.approvePeople,@"approvePeople",model.physicsRegion,@"physicsRegion",model.activeType,@"activityType",model.infoLevel,@"informationLevel",model.isLocal,@"informationRegion",model.mainKeyWord,@"mainKeyWord",model.subKeyWord,@"subKeyWord",model.ori_title,@"singleMessageTitle",nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"goToTheSingleViewRp" object:nil userInfo:userInfo11b];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
